package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sun.org.apache.xml.internal.utils.res.XResources_ja_JP_HI;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class SpuServiceImpl implements SpuService {
    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    /**
     * @Description:商品审核
     * @Author: 陈安
     * @Date: 12-07
     */
    @Override
    public void audit(String id) {
        //先通过id查询出来spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //做一下健壮性的判断
        if(spu==null){
            throw new RuntimeException("没有此商品");
        }
        //判断当前商品是否处于删除状态,因为删除状态的商品是不能够进行商品审核和上架的
        String isDelete = spu.getIsDelete();
        if("1".equals(isDelete)){
            throw new RuntimeException("次商品处于删除状态,不能够进行审核");
        }
        spu.setStatus("1");
        spu.setIsMarketable("1");
        //进行修改
        spuMapper.updateByPrimaryKeySelective(spu);

    }

    /**
     * @Description:
     * @Author: 陈安
     * @Date: ${date} ${time}
     * @Param: ${param}
     * @Return: ${return}
     */
    @Override
    public void pull(String id) {
        //通过id查询出来spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu==null){
            throw new RuntimeException("查不到这个商品");
        }
        String isDelete = spu.getIsDelete();
        if("1".equals(isDelete)){
            throw new RuntimeException("商品已经处于删除状态");
        }

        //商品改为下架状态
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    public void put(String id) {
        //先根据id查询出来spu的信息
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu==null){
            throw new RuntimeException("商品不存在");
        }
        String status = spu.getStatus();
        if("0".equals(status)){
            throw new RuntimeException("商品未通过审核");
        }

        //商品改为上架状态
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 查询全部列表
     *
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     *
     * @param goods
     */
    @Override
    public void add(Goods goods) {
        //1 :添加spu
        Spu spu = goods.getSpu();
        //设置分布式id
        long spuId = idWorker.nextId();
        spu.setId(String.valueOf(spuId));
        //设置删除状态
        spu.setIsDelete("0");
        //设置上架状态
        spu.setIsMarketable("0");
        //设置审核状态
        spu.setStatus("0");

        spuMapper.insertSelective(spu);

        // 2:添加sku集合

        this.saveSkuList(goods);


    }

    //添加sku的数据
    private void saveSkuList(Goods goods) {
        Spu spu = goods.getSpu();

        //设置品牌与分类的关联关系
        //先通过spu拿到这两个id,然后通过查询,看这两个id有没有关系
        CategoryBrand categoryBrand=new CategoryBrand();
        categoryBrand.setCategoryId(spu.getCategory3Id());
        categoryBrand.setBrandId(spu.getBrandId());
        int i = categoryBrandMapper.selectCount(categoryBrand);

        //判断是不是有关系的
        if(i==0){//表示品牌与分类还没有关联,我们给他们设置关联关系
            categoryBrandMapper.insertSelective(categoryBrand);

        }


        //获取sku的集合
        List<Sku> skuList = goods.getSkuList();
        // 先是判断这个sku有没有
        if (skuList != null) {
            //因为这个是集合,所以我们要循环获取
            for (Sku sku : skuList) {
                //设置skuid
                long skuid = idWorker.nextId();
                sku.setId(String.valueOf(skuid));
                //设置sku的规格数据spec
                String spec = sku.getSpec();
                if (StringUtils.isEmpty(spec)) {
                    //这个表示规格假如是空的,我们就给他加上{}
                    sku.setSpec("{}");
                }
                //设置名称(spu名称+规格)
                String name = spu.getName();
                //将规格的json类型转化为map,用JSON.parseObject
                Map<String, String> map = JSON.parseObject(sku.getSpec(), Map.class);
                if (map != null && map.size() > 0) {
                    for (String s : map.values()) {
                        //进行拼接,由于数据库的存储是有空格的,所以这里拼接上空格
                    name=name+" "+s;
                    }
                }
                sku.setName(name);

                //设置spuId,因为我们的sku里面有spuid这个字段
                sku.setSpuId(spu.getId());

                //设置创建和修改时间
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());

                //设置商品分类id,由于要和商品的分类打交道,所以我们这里要引入categoryMapper
                Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
                sku.setCategoryId(category.getId());

                //设置商品分类名称
                sku.setCategoryName(category.getName());

                //查询品牌名称
                Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
                sku.setBrandName(brand.getName());

                //将当前的sku添加到数据库里面
                skuMapper.insertSelective(sku);

            }

        }

    }


    /**
     * 修改
     *
     * @param goods
     */
    @Override
    public void update(Goods goods) {

        //先通过spu来更新spu
        Spu spu = goods.getSpu();
        spuMapper.updateByPrimaryKey(spu);

        //这个的更新是通过先删除在保存
        Example example=new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spu.getId());
        int delete = skuMapper.deleteByExample(example);
        saveSkuList(goods);

    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu==null){
            throw  new RuntimeException("没有这个商品");
        }
        String isMarketable = spu.getIsMarketable();
        if("1".equals(isMarketable)){
            throw  new RuntimeException("必须先下架才可以进行删除");
        }
        //未审核
        spu.setStatus("0");
        //删除
        spu.setIsDelete("1");
        spuMapper.updateByPrimaryKeySelective(spu);


    }

    /**
     * @Description:商品物理删除
     * @Author: 陈安
     * @Date: 12-07
     */
    @Override
    public void realDel(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu == null){
            throw  new RuntimeException("没有这个商品");
        }
        String isDelete = spu.getIsDelete();
        if("0".equals(isDelete)){
            throw  new RuntimeException("这个商品还未被删除");
        }
        spuMapper.deleteByPrimaryKey(spu);

    }

    /**
     * @Description:商品还原
     * @Author: 陈安
     * @Date: 12-07
     */
    @Override
    public void restore(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu==null){
            throw  new RuntimeException("没有这个商品");
        }
        String isDelete = spu.getIsDelete();
        if("0".equals(isDelete)){
            throw  new RuntimeException("这个商品还未被删除");
        }

        spu.setIsDelete("0");
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);

    }


    /**
     * 条件查询
     *
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<Spu>) spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     *
     * @param searchMap 查询条件
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        return (Page<Spu>) spuMapper.selectByExample(example);
    }

    @Override
    public Goods findGoodsById(String id) {
        Goods goods=new Goods();
        //先根据spu的id查询出来spu的信息,然后将spu放入到goods中,准备返回
        Spu spu = spuMapper.selectByPrimaryKey(id);
//        if(spu==null){
//             new throw Exception("没有查到对应的商品信息");
//        }
        goods.setSpu(spu);
        //再根据spu的id去查询到sku的信息,然后将其存入到goods里面去
        Example example=new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<Sku> skus = skuMapper.selectByExample(example);
        goods.setSkuList(skus);

        return goods;
    }

    /**
     * 构建查询对象
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 主键
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 货号
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andEqualTo("sn", searchMap.get("sn"));
            }
            // SPU名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 副标题
            if (searchMap.get("caption") != null && !"".equals(searchMap.get("caption"))) {
                criteria.andLike("caption", "%" + searchMap.get("caption") + "%");
            }
            // 图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // 售后服务
            if (searchMap.get("saleService") != null && !"".equals(searchMap.get("saleService"))) {
                criteria.andLike("saleService", "%" + searchMap.get("saleService") + "%");
            }
            // 介绍
            if (searchMap.get("introduction") != null && !"".equals(searchMap.get("introduction"))) {
                criteria.andLike("introduction", "%" + searchMap.get("introduction") + "%");
            }
            // 规格列表
            if (searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems"))) {
                criteria.andLike("specItems", "%" + searchMap.get("specItems") + "%");
            }
            // 参数列表
            if (searchMap.get("paraItems") != null && !"".equals(searchMap.get("paraItems"))) {
                criteria.andLike("paraItems", "%" + searchMap.get("paraItems") + "%");
            }
            // 是否上架
            if (searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable"))) {
                criteria.andEqualTo("isMarketable", searchMap.get("isMarketable"));
            }
            // 是否启用规格
            if (searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec"))) {
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andEqualTo("isDelete", searchMap.get("isDelete"));
            }
            // 审核状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andEqualTo("status", searchMap.get("status"));
            }

            // 品牌ID
            if (searchMap.get("brandId") != null) {
                criteria.andEqualTo("brandId", searchMap.get("brandId"));
            }
            // 一级分类
            if (searchMap.get("category1Id") != null) {
                criteria.andEqualTo("category1Id", searchMap.get("category1Id"));
            }
            // 二级分类
            if (searchMap.get("category2Id") != null) {
                criteria.andEqualTo("category2Id", searchMap.get("category2Id"));
            }
            // 三级分类
            if (searchMap.get("category3Id") != null) {
                criteria.andEqualTo("category3Id", searchMap.get("category3Id"));
            }
            // 模板ID
            if (searchMap.get("templateId") != null) {
                criteria.andEqualTo("templateId", searchMap.get("templateId"));
            }
            // 运费模板id
            if (searchMap.get("freightId") != null) {
                criteria.andEqualTo("freightId", searchMap.get("freightId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
